package com.cy.java.thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

public class ThreadExecutorPoolTests {
    public static  void main(String[] args) {

        //创建一个任务队列
        BlockingQueue<Runnable> workQueue=new ArrayBlockingQueue<>(1);

        //创建线程工厂
        ThreadFactory threadFactory=new ThreadFactory() {
            private AtomicLong al=new AtomicLong(1);//线程安全的对象
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r,"cgb2007-thread-"+al.getAndIncrement());
            }
        };
        //创建一个线程池
        ThreadPoolExecutor threadPoolExecutor=
                new ThreadPoolExecutor(
                        2,
                        3,
                        60,
                        TimeUnit.SECONDS,
                        workQueue,
                        threadFactory,
                        new ThreadPoolExecutor.CallerRunsPolicy()
                        );
        threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                String tname=Thread.currentThread().getName();
                System.out.println(tname+"->task-01");
                try {Thread.sleep(3000);}catch (Exception e){}
            }
        });
        threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                String tname=Thread.currentThread().getName();
                System.out.println(tname+"->task-02");
                try {Thread.sleep(3000);}catch (Exception e){}
            }
        });
        threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                String tname=Thread.currentThread().getName();
                System.out.println(tname+"->task-03");
                try {Thread.sleep(3000);}catch (Exception e){}
            }
        });
        threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                String tname=Thread.currentThread().getName();
                System.out.println(tname+"->task-04");
                try {Thread.sleep(3000);}catch (Exception e){}
            }
        });
        threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                String tname=Thread.currentThread().getName();
                System.out.println(tname+"->task-05");
            }
        });
    }
}
